package com.yanghongyue.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanghongyue.reggie.bean.Cart;
import com.yanghongyue.reggie.common.BaseContext;
import com.yanghongyue.reggie.mapper.CartMapper;
import com.yanghongyue.reggie.service.CartService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author HongyueYang
 */
@Service
public class CartServcieImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    //添加购物车
    @Override
    public Cart addCart(Cart cart) {

        //获取当前用户的id
        Long currentId = BaseContext.getCurrentId();
        //给对象设置用户id
        cart.setUserId(currentId);
        //获取当前传来的数据
        Long dishId = cart.getDishId();
        //创建条件构造器
        QueryWrapper<Cart> wrapper =new QueryWrapper<>();
        wrapper.eq("user_id",currentId);
        //判断是菜品还是套餐
        if (dishId!=null){
            wrapper.eq("dish_id",dishId);
        }else {
            wrapper.eq("setmeal_id",cart.getSetmealId());
        }
        //根据条件查询当前用户购物车数据（本次提交的）
        Cart cartData = this.getOne(wrapper);
        //判断是否存在
        if (cartData!=null){
            //存在，数量加1
            cartData.setNumber(cartData.getNumber()+1);
            //更新
            this.updateById(cartData);
        }else {
            //不存在，数量设置为1
            cart.setNumber(1);
            cart.setCreateTime(LocalDateTime.now());
            //执行保存
            this.save(cart);
            cartData=cart;
        }
        //返回结果
        return cartData;

    }
}
